package com.service.impl;

import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;
import com.entity.PageBean;
import com.entity.User;
import com.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao dao=new UserDaoImpl();

    @Override
    public List<User> findAll(){
        //调用dao完成查询
        return dao.findAll();
    }

   public User login(User user) {
        return dao.findUserByUsernameAndPassword(user.getUsername(),user.getPassword());
    }

    @Override
    public void addUser(User user) {
        dao.add(user);
    }

    @Override
    public void deleteUser(String id) {
        dao.delete(Integer.parseInt(id));//转为数字类型

    }

    @Override
    public User findUserById(String id) {
        return dao.findById(Integer.parseInt(id));
    }

    @Override
    public void updateUser(User user) {
        dao.update(user);
    }

    @Override
    public void delSelectedUser(String[] ids) {
        if (ids!=null&&ids.length>0){//防止空指针异常
            //1、遍历数组
            for (String id:ids){
                //2、调用dao删除
                dao.delete(Integer.parseInt(id));
                //删除的dao已经有了
            }
        }

    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows) {
        int currentPage=Integer.parseInt(_currentPage);
        int rows=Integer.parseInt(_rows);
        if (currentPage<=0){
            currentPage=1;
        }



        

        //1、创建空的PageBean对象
        PageBean<User> pb=new PageBean<User>();
        //2、设置参数
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);
        //3、调用dao查询总记录数
        int totalCount=dao.findTotalCount();
        pb.setTotalCount(totalCount);
        //4、调用dao查询List集合
        //计算开始的记录索引
        int start=(currentPage-1)*rows;
        List<User> list=dao.findByPage(start,rows);
        pb.setList(list);
        //5、计算总记录数totalPage
        int totalPage=(totalCount % rows) ==0 ? totalCount/rows : (totalCount/rows)+1;
        pb.setTotalPage(totalPage);
        return pb;
    }

}
